<template>
  <div class="login-page">
    <!-- 登录卡片 -->
    <div class="login-card-container">
      <el-card class="login-card">
        <!-- 卡片标题区 -->
        <div class="login-header">
          <el-icon class="header-icon"><School /></el-icon>
          <h2 class="login-title">欢迎使用学校行为规范管理系统</h2>
          <p class="login-desc">请输入账号密码登录</p>
        </div>

        <!-- 登录表单 -->
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="formRef" 
          label-width="80px"
          class="login-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input 
              v-model="form.username" 
              placeholder="请输入用户名" 
              prefix-icon="User"
              class="form-input"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input 
              v-model="form.password" 
              type="password" 
              placeholder="请输入密码" 
              prefix-icon="Lock"
              class="form-input"
            />
          </el-form-item>
          <el-form-item class="login-btn-group">
            <el-button 
              type="primary" 
              @click="handleLogin" 
              class="login-btn"
              :loading="loading"
            >
              登录
            </el-button>
          </el-form-item>
          <div class="login-links">
            <el-button 
              type="text" 
              class="register-btn" 
              @click="openRegisterDialog"
            >
              注册
            </el-button>
            <el-button 
              type="text" 
              class="forgot-btn" 
              @click="openForgotDialog"
            >
              忘记密码？
            </el-button>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 注册对话框 -->
    <el-dialog 
      v-model="registerDialogVisible" 
      title="教师注册" 
      :close-on-click-modal="false"
      class="custom-dialog"
      @close="handleRegisterClose"
    >
      <el-form 
        :model="registerForm" 
        :rules="registerRules" 
        ref="registerFormRef" 
        label-width="100px"
        class="register-form"
      >
        <el-form-item label="账号名" prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="请输入注册账号名" 
            prefix-icon="User"
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="重复密码" prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码" 
            prefix-icon="Lock"
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="教师口令" prop="teacherPassword">
          <el-input 
            v-model="registerForm.teacherPassword" 
            type="password" 
            placeholder="请输入教师口令" 
            prefix-icon="Key"
            class="form-input"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            @click="registerDialogVisible = false"
            class="cancel-btn"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleRegister"
            :loading="registerLoading"
            class="submit-btn"
          >
            注册
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 忘记密码对话框 -->
    <el-dialog 
      v-model="forgotDialogVisible" 
      title="重置密码" 
      :close-on-click-modal="false"
      class="custom-dialog"
      @close="handleForgotPwdClose"
    >
      <el-form 
        :model="forgotForm" 
        :rules="forgotRules" 
        ref="forgotFormRef" 
        label-width="100px"
        class="forgot-form"
      >
        <el-form-item label="教师口令" prop="adminPassword">
          <el-input 
            v-model="forgotForm.adminPassword" 
            type="password" 
            placeholder="请输入教师口令" 
            prefix-icon="Key"
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="forgotForm.newPassword" 
            type="password" 
            placeholder="请输入新密码" 
            prefix-icon="Lock"
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="重复新密码" prop="confirmNewPassword">
          <el-input 
            v-model="forgotForm.confirmNewPassword" 
            type="password" 
            placeholder="请再次输入新密码" 
            prefix-icon="Lock"
            class="form-input"
          />
        </el-form-item>
        <el-form-item>
          <p class="forgot-desc">
            教师账号通过口令重设密码，如忘记口令请与管理员联系重置口令。
            学生账号请与班主任老师联系，重置密码。
          </p>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            @click="forgotDialogVisible = false"
            class="cancel-btn"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleForgotPassword"
            :loading="forgotLoading"
            class="submit-btn"
          >
            重置
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import type { ElForm } from 'element-plus';
import { ElMessage } from 'element-plus';
import { getBasicUserInfo, login } from '../../api/auth';
import { forgotPassword } from '../../api/auth';
import { registerTeacher } from '../../api/register';
import { setToken } from '../../utils/storage';
import { School } from '@element-plus/icons-vue';
import { useAuthStore } from '../../store/authStore';
import type { User } from '../../types/auth';

// 表单状态
const formRef = ref<InstanceType<typeof ElForm>>();
const loading = ref(false);
const form = reactive({
  username: '',
  password: ''
});
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

// 注册对话框状态
const registerDialogVisible = ref(false);
const registerFormRef = ref<InstanceType<typeof ElForm>>();
const registerLoading = ref(false);
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  teacherPassword: ''
});
const registerRules = {
  username: [{ required: true, message: '请输入账号名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { 
      validator: (_: any, value: string, callback: any) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  teacherPassword: [{ required: true, message: '请输入教师口令', trigger: 'blur' }]
};

// 忘记密码对话框状态
const forgotDialogVisible = ref(false);
const forgotFormRef = ref<InstanceType<typeof ElForm>>();
const forgotLoading = ref(false);
const forgotForm = reactive({
  adminPassword: '',
  newPassword: '',
  confirmNewPassword: ''
});
const forgotRules = {
  adminPassword: [{ required: true, message: '请输入教师口令', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (_: any, value: string, callback: any) => {
        if (value !== forgotForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 路由和状态管理
const router = useRouter();

// 登录缓存
const authStore = useAuthStore();

// 登录处理
const handleLogin = async () => {
  if (!formRef.value) return;
  try {
    loading.value = true;
    await formRef.value.validate();
    const res = await login(form);
    if (res.code === 200) {
      setToken(res.content.token);
      ElMessage.success('登录成功');

      // 记录用户基本信息到缓存
      const userRes = await getBasicUserInfo();
      const userInfo: User = {
        id: userRes.user_id,
        realName: userRes.name,
        role: userRes.role
      };
      authStore.setUser(userInfo)

      router.push('/');
    } else {
      ElMessage.error(res.msg || '登录失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '登录异常');
  } finally {
    loading.value = false;
  }
};

// 打开注册对话框
const openRegisterDialog = () => {
  registerDialogVisible.value = true;
};

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return;
  try {
    registerLoading.value = true;
    await registerFormRef.value.validate();
    
    // 调用注册接口
    const res = await registerTeacher({
      username: registerForm.username,
      password: registerForm.password,
      teacher_password: registerForm.teacherPassword
    });
    
    if (res.code === 200) {
      ElMessage.success('注册成功，请登录');
      registerDialogVisible.value = false;
      // 清空表单
      Object.keys(registerForm).forEach(key => {
        registerForm[key as keyof typeof registerForm] = '';
      });
    } else {
      ElMessage.error(res.msg || '注册失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '注册异常');
  } finally {
    registerLoading.value = false;
  }
};

// 打开忘记密码对话框
const openForgotDialog = () => {
  forgotDialogVisible.value = true;
};

// 处理忘记密码
const handleForgotPassword = async () => {
  if (!forgotFormRef.value) return;
  try {
    forgotLoading.value = true;
    await forgotFormRef.value.validate();
    
    // 调用忘记密码接口
    const res = await forgotPassword({
      admin_password: forgotForm.adminPassword,
      new_password: forgotForm.newPassword
    });
    
    if (res.code === 200) {
      ElMessage.success('密码重置成功，请登录');
      forgotDialogVisible.value = false;
      // 清空表单
      Object.keys(forgotForm).forEach(key => {
        forgotForm[key as keyof typeof forgotForm] = '';
      });
    } else {
      ElMessage.error(res.msg || '密码重置失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '密码重置异常');
  } finally {
    forgotLoading.value = false;
  }
};

// 注册对话框关闭事件
const handleRegisterClose = () => {
  // 清空注册表单
  registerForm.username = '';
  registerForm.password = '';
  registerForm.teacherPassword = '';
  // 重置表单验证状态
  if (registerFormRef.value) {
    registerFormRef.value.resetFields();
  }
};

// 忘记密码对话框关闭事件
const handleForgotPwdClose = () => {
  // 清空密码重置表单
  forgotForm.adminPassword = '';
  forgotForm.confirmNewPassword = '';
  forgotForm.newPassword = '';
  // 重置表单验证状态
  if (forgotFormRef.value) {
    forgotFormRef.value.resetFields();
  }
};
</script>

<style scoped>
/* 页面容器（全屏覆盖） */
.login-page {
  position: relative;
  min-height: 100vh;
  width: 100%;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, var(--bg-color-1) 0%, var(--bg-color-2) 100%);
  transition: background 0.5s ease;
}

/* 登录卡片容器（居中+阴影） */
.login-card-container {
  width: 100%;
  max-width: 500px;
  perspective: 1000px;
  margin-top: -160px;
}

/* 登录卡片样式 */
.login-card {
  background-color: #f0f2f5;
  border: none;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  padding: 30px 40px;
  transform-style: preserve-3d;
  transition: all 0.3s ease;
}

.login-card:hover {
  transform: translateY(-5px) rotateX(2deg);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
}

/* 标题区样式 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
  color: var(--text-primary);
}

.header-icon {
  font-size: 40px;
  color: #409eff;
  margin-bottom: 15px;
  transition: transform 0.3s ease;
}

.login-card:hover .header-icon {
  transform: scale(1.1) rotate(5deg);
}

.login-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 10px 0;
}

.login-desc {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

/* 表单样式 */
.login-form {
  margin-top: 20px;
}

.form-input {
  background-color: rgba(255, 255, 255, 0.05);
  border-color: var(--border-color);
  color: var(--text-primary);
}

.form-input::placeholder {
  color: var(--text-secondary);
  opacity: 0.7;
}

/* 按钮样式 */
.login-btn-group {
  margin-top: 20px;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  background: linear-gradient(90deg, #409eff, #69b1ff);
  border: none;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background: linear-gradient(90deg, #3088e2, #5aa8f7);
  transform: translateY(-2px) scale(1.02);
}

.login-btn:active {
  transform: scale(0.98);
}

/* 链接样式 */
.login-links {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.register-btn, .forgot-btn {
  color: #409eff;
  padding: 5px 10px;
  transition: all 0.2s ease;
}

.register-btn:hover, .forgot-btn:hover {
  color: #3088e2;
  transform: translateY(-1px);
}

/* 对话框样式 */
.custom-dialog {
  --el-dialog-background-color: #f0f2f5;
  --el-dialog-border-radius: 12px;
}

.register-form, .forgot-form {
  margin-top: 10px;
}

.forgot-desc {
  color: #606266;
  font-size: 12px;
  line-height: 1.6;
  margin: 5px 0 0 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn {
  transition: all 0.2s ease;
}

.cancel-btn:hover {
  transform: translateY(-1px);
}

.submit-btn {
  background: linear-gradient(90deg, #409eff, #69b1ff);
  border: none;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: linear-gradient(90deg, #3088e2, #5aa8f7);
  transform: translateY(-2px) scale(1.02);
}

.submit-btn:active {
  transform: scale(0.98);
}

/* 适配暗色模式下的Element组件样式 */
.dark .el-form-item__label {
  color: var(--text-primary) !important;
}

.dark .el-input__wrapper {
  background-color: rgba(255, 255, 255, 0.05) !important;
}

.dark .el-input__inner {
  color: var(--text-primary) !important;
}

.dark .custom-dialog {
  --el-dialog-background-color: #1f2329;
}

.dark .forgot-desc {
  color: #c0c4cc;
  background-color: #2c3038;
}
</style>